// pages/labor/detail/detail.js
const app = getApp()

Page({
  data: {
    laborInfo: {},
    loading: true,
    isOwner: false,
    hasApplied: false,
    showApplyModal: false,
    applicationNote: ''
  },

  onLoad(options) {
    const { id } = options
    if (id) {
      this.loadLaborDetail(id)
    }
  },

  async loadLaborDetail(id) {
    wx.showLoading({ title: '加载中...' })
    
    try {
      const result = await app.utils.request({
        url: `/labor/detail/${id}`,
        method: 'GET'
      })
      
      if (result.code === 200) {
        const laborInfo = result.data
        
        // 调试：打印返回的数据
        console.log('劳务详情数据:', laborInfo)
        console.log('图片数据:', laborInfo.images)
        
        // 添加状态文本
        laborInfo.statusText = this.getStatusText(laborInfo.status)
        
        // 处理信用分等级和颜色
        if (laborInfo.publisherCredit !== undefined) {
          const creditInfo = this.getCreditInfo(laborInfo.publisherCredit)
          laborInfo.creditLevel = creditInfo.level
          laborInfo.creditColor = creditInfo.color
        }
        
        // 处理劳务类型信息（如果后端没有返回，使用默认值）
        if (!laborInfo.typeName && laborInfo.typeId) {
          const typeInfo = this.getTypeInfoById(laborInfo.typeId)
          laborInfo.typeName = typeInfo.name
          laborInfo.typeIcon = typeInfo.icon
          laborInfo.typeColor = typeInfo.color
        }
        
        // 检查是否是发布者
        const isOwner = app.globalData.userInfo && 
                       app.globalData.userInfo.id === laborInfo.publisherId
        
        this.setData({
          laborInfo,
          isOwner,
          loading: false
        })
      } else {
        throw new Error(result.message || '获取劳务详情失败')
      }
    } catch (error) {
      console.error('获取劳务详情失败:', error)
      this.setData({ loading: false })
      app.utils.showError(error.message || '获取劳务详情失败')
    }
    
    wx.hideLoading()
  },

  showApplyModal() {
    this.setData({
      showApplyModal: true,
      applicationNote: ''
    })
  },

  hideApplyModal() {
    this.setData({
      showApplyModal: false,
      applicationNote: ''
    })
  },

  preventClose(e) {
    // 阻止事件冒泡，防止点击输入区域时关闭弹窗
    e.stopPropagation()
  },

  onApplicationNoteInput(e) {
    this.setData({
      applicationNote: e.detail.value
    })
  },

  async confirmApply() {
    const { applicationNote } = this.data
    
    // 如果按钮是禁用状态，直接返回
    if (!applicationNote.trim()) {
      return
    }

    wx.showLoading({ title: '申请中...' })
    
    try {
      const result = await app.utils.request({
        url: '/labor/apply',
        method: 'POST',
        data: {
          laborId: this.data.laborInfo.id,
          applicationNote: applicationNote.trim()
        }
      })
      
      wx.hideLoading()
      
      if (result.code === 200) {
        wx.showToast({
          title: '申请成功',
          icon: 'success'
        })
        
        // 更新申请人数和状态
        const updatedLaborInfo = { ...this.data.laborInfo }
        updatedLaborInfo.applicationCount = (updatedLaborInfo.applicationCount || 0) + 1
        
        // 更新状态并关闭弹窗
        this.setData({
          hasApplied: true,
          showApplyModal: false,
          applicationNote: '',
          laborInfo: updatedLaborInfo
        })
      } else {
        throw new Error(result.message || '申请失败')
      }
    } catch (error) {
      wx.hideLoading()
      console.error('申请劳务失败:', error)
      app.utils.showError(error.message || '申请失败')
    }
  },

  cancelJob() {
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个工作发布吗？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...' })
          
          try {
            const result = await app.utils.request({
              url: `/labor/close/${this.data.laborInfo.id}`,
              method: 'POST'
            })
            
            wx.hideLoading()
            
            if (result.code === 200) {
              wx.showToast({
                title: '已取消发布',
                icon: 'success'
              })
              
              // 更新状态
              this.setData({
                'laborInfo.status': 'closed'
              })
              
              setTimeout(() => {
                wx.navigateBack()
              }, 1500)
            } else {
              throw new Error(result.message || '取消发布失败')
            }
          } catch (error) {
            wx.hideLoading()
            console.error('取消发布失败:', error)
            app.utils.showError(error.message || '取消发布失败')
          }
        }
      }
    })
  },

  confirmComplete() {
    wx.showModal({
      title: '确认完成',
      content: '确认工作已完成？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...' })
          
          setTimeout(() => {
            wx.hideLoading()
            wx.showToast({
              title: '已确认完成',
              icon: 'success'
            })
            
            this.setData({
              'laborInfo.status': 'completed'
            })
          }, 1000)
        }
      }
    })
  },

  rateJob() {
    wx.navigateTo({
      url: `/pages/rate/rate?orderId=${this.data.laborInfo.id}&type=labor`
    })
  },

  contactPublisher() {
    wx.navigateTo({
      url: `/pages/chat/chat?userId=${this.data.laborInfo.publisherId}&userName=${this.data.laborInfo.publisherName}`
    })
  },

  copyContact(e) {
    const { type, value } = e.currentTarget.dataset
    
    wx.setClipboardData({
      data: value,
      success: () => {
        wx.showToast({
          title: `${type === 'phone' ? '手机号' : type === 'qq' ? 'QQ号' : '微信号'}已复制`,
          icon: 'success',
          duration: 2000
        })
      },
      fail: () => {
        wx.showToast({
          title: '复制失败',
          icon: 'error'
        })
      }
    })
  },

  getStatusText(status) {
    const statusMap = {
      'recruiting': '招聘中',
      'filled': '已招满',
      'completed': '已完成',
      'closed': '已关闭'
    }
    return statusMap[status] || '未知状态'
  },

  // 根据类型ID获取类型信息（如果后端没返回类型信息时使用）
  getTypeInfoById(typeId) {
    const typeMap = {
      1: { name: '家教辅导', icon: '📚', color: '#10b981' },
      2: { name: '兼职工作', icon: '💼', color: '#3b82f6' },
      3: { name: '技能服务', icon: '🎯', color: '#8b5cf6' },
      4: { name: '生活服务', icon: '🏠', color: '#f59e0b' },
      5: { name: '学术研究', icon: '🔬', color: '#ef4444' },
      6: { name: '活动协助', icon: '🎪', color: '#f97316' },
      7: { name: '体力劳动', icon: '💪', color: '#6b7280' },
      8: { name: '创意设计', icon: '🎨', color: '#ec4899' }
    }
    return typeMap[typeId] || { name: '其他', icon: '💼', color: '#667eea' }
  },

  // 根据信用分获取等级信息
  getCreditInfo(creditScore) {
    if (creditScore >= 95) {
      return { level: '极佳', color: '#10b981' } // 绿色
    } else if (creditScore >= 85) {
      return { level: '优秀', color: '#3b82f6' } // 蓝色
    } else if (creditScore >= 75) {
      return { level: '良好', color: '#f59e0b' } // 橙色
    } else if (creditScore >= 60) {
      return { level: '一般', color: '#ef4444' } // 红色
    } else {
      return { level: '较差', color: '#9ca3af' } // 灰色
    }
  },

  viewApplicants() {
    wx.navigateTo({
      url: `/pages/labor/applicants/applicants?laborId=${this.data.laborInfo.id}`
    })
  },

  // 预览图片
  previewImage(e) {
    const { index, urls } = e.currentTarget.dataset
    wx.previewImage({
      current: urls[index],
      urls: urls
    })
  }
})
